package ua.pp.bizon.cripto.authorization;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import ua.pp.bizon.cripto.configuration.Configuration;
import ua.pp.bizon.cripto.keystore.AES128;
import ua.pp.bizon.cripto.keystore.CryptoException;

public class CashedUI implements UI {

    public static String PATH_CREDENTIALS = "credentials.properties";
    private static final String PASSWORD = "password";
    private static final String USERNAME = "username";

    private UI ui;

    public CashedUI(UI ui) {
        super();
        this.ui = ui;
    }

    @Override
    public void login(Credentials credentials) throws IOException, CryptoException {
        Properties login = new Properties();
        File f = getFile();
        if (f.exists()) {
            login.load(getInputStream(f));
            credentials.setUsername(login.getProperty(USERNAME));
            credentials.setHashedPassword(AES128.asString(login.getProperty(PASSWORD)));
        }
        if (credentials.getUsername() == null) {
            f.delete();
            ui.login(credentials);
            login.setProperty(USERNAME, credentials.getUsername());
            login.setProperty(PASSWORD, AES128.asHex(credentials.getHashedPassword()));
            login.store(getOutputStream(f), "password hashed");
        }
    }

    protected OutputStream getOutputStream(File f) throws FileNotFoundException {
        return new FileOutputStream(f);
    }

    protected InputStream getInputStream(File f) throws FileNotFoundException {
        return new FileInputStream(f);
    }

    protected File getFile() {
        return new File(PATH_CREDENTIALS);
    }

    @Override
    public Configuration configure(Configuration configuration) {
        return ui.configure(configuration);
    }

    @Override
    public void done() {
        ui.done();
    }
}
